package com.group15.phms;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.group15.phms.DeleteDialogFragment.DeleteDialogListener;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.support.v4.app.NavUtils;

public class Medications extends ListActivity implements DeleteDialogListener {
	SharedPreferences logins;
	DatabaseHelper db;
	SimpleAdapter adapter;
	String currentUser;
	ArrayList<Map<String, String>> data;
	List<Medication> meds;
	ListView ItemList;
	String deleteGenName;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_medications);
		// Show the Up button in the action bar.
		setupActionBar();
		logins = getSharedPreferences("logins",MODE_PRIVATE);
		currentUser = logins.getString("currentUser","INVALID");
		db= new DatabaseHelper(getApplicationContext());

		meds = db.getMedications(currentUser);	
		
		Collections.sort(meds, new MedicationComparator());
		
		data = new ArrayList<Map<String, String>>();
		for (Medication med : meds) {
		    Map<String, String> datum = new HashMap<String, String>(2);
		    datum.put("name", med.getName());
		    datum.put("genName", med.getGenName());
		    data.add(datum);
		}
		
		
		adapter = new SimpleAdapter(this, data,
                                      R.layout.medication_row,
                                      new String[] {"name", "genName"},
                                      new int[] {R.id.toptext,
                                                 R.id.bottomtext});
									
		ListView itemList=(ListView)findViewById(android.R.id.list);
		itemList.setAdapter(adapter);
		itemList.setEmptyView(findViewById(R.id.empty));
		db.closeDB();
		
		this.getListView().setLongClickable(true);
		this.getListView().setOnItemLongClickListener(new OnItemLongClickListener() {
		    public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id) {
		    	DialogFragment f = new DeleteDialogFragment();
		        f.show(getFragmentManager(), "DeleteDialogFragment");
		        deleteGenName = meds.get(position).getGenName();
		        return true;
		    }
		});
		
	}
	
	@Override
	public void onRestart()
	{
		super.onRestart();
		db= new DatabaseHelper(getApplicationContext());
		meds = db.getMedications(currentUser);
		Collections.sort(meds, new MedicationComparator());
		data = new ArrayList<Map<String, String>>();
		for (Medication med : meds) {
		    Map<String, String> datum = new HashMap<String, String>(2);
		    datum.put("name", med.getName());
		    datum.put("genName", med.getGenName());
		    data.add(datum);
		}
		adapter = new SimpleAdapter(this, data,
                R.layout.medication_row,
                new String[] {"name", "genName"},
                new int[] {R.id.toptext,
                           R.id.bottomtext});
		ListView itemList=(ListView)findViewById(android.R.id.list);
		itemList.setAdapter(adapter);
		itemList.setEmptyView(findViewById(R.id.empty));
		adapter.notifyDataSetChanged();
		db.closeDB();
	}
	
	@Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
          // Get the item that was clicked
        Map<String, String> m = (Map<String, String>) this.getListView().getItemAtPosition(position);
        Intent intent = new Intent(this, MedicationInfo.class);
        intent.putExtra("genName", m.get("genName"));
        startActivity(intent); 
    }

	/**
	 * Set up the {@link android.app.ActionBar}.
	 */
	private void setupActionBar() {

		getActionBar().setDisplayHomeAsUpEnabled(true);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.medications, menu);
		return true;
	}
	Intent intent;
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			// This ID represents the Home or Up button. In the case of this
			// activity, the Up button is shown. Use NavUtils to allow users
			// to navigate up one level in the application structure. For
			// more details, see the Navigation pattern on Android Design:
			//
			// http://developer.android.com/design/patterns/navigation.html#up-vs-back
			//
			NavUtils.navigateUpFromSameTask(this);
			return true;
		case R.id.action_logout:
			intent = new Intent(this, Login.class);
	    	startActivity(intent);
	    	finish();
			return true;
		case R.id.action_search:
			intent = new Intent(this, Search.class);
	    	startActivity(intent);
			return true;
		case R.id.addbutton:
			intent = new Intent(this, AddMedication.class);
	    	startActivity(intent);
			return true;
			
		}
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	public void onPositiveClick()
	{
		db= new DatabaseHelper(getApplicationContext());
		db.deleteMedication(deleteGenName, currentUser);
		Toast.makeText(getApplicationContext(),"Medication deleted successfully", Toast.LENGTH_SHORT).show();
		meds = db.getMedications(currentUser);
		data = new ArrayList<Map<String, String>>();
		for (Medication med : meds) {
		    Map<String, String> datum = new HashMap<String, String>(2);
		    datum.put("name", med.getName());
		    datum.put("genName", med.getGenName());
		    data.add(datum);
		}
		adapter = new SimpleAdapter(this, data,
                R.layout.medication_row,
                new String[] {"name", "genName"},
                new int[] {R.id.toptext,
                           R.id.bottomtext});
		ListView itemList=(ListView)findViewById(android.R.id.list);
		itemList.setAdapter(adapter);
		itemList.setEmptyView(findViewById(R.id.empty));
		adapter.notifyDataSetChanged();
		db.closeDB();
	}

}

class MedicationComparator implements Comparator<Medication> {
    @Override
    public int compare(Medication m1, Medication m2) {
        return m1.getName().toLowerCase().compareTo(m2.getName().toLowerCase());
    }
}

class DeleteDialogFragment extends DialogFragment {
	String callingActivity;
    
	/* The activity that creates an instance of this dialog fragment must
     * implement this interface in order to receive event callbacks.
     * Each method passes the DialogFragment in case the host needs to query it. */
    public interface DeleteDialogListener {
        public void onPositiveClick();
    }
    
    // Use this instance of the interface to deliver action events
    DeleteDialogListener mListener;
    
    // Override the Fragment.onAttach() method to instantiate the NoticeDialogListener
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        callingActivity = (activity.getClass().getSimpleName());
        // Verify that the host activity implements the callback interface
        try {
            // Instantiate the NoticeDialogListener so we can send events to the host
            mListener = (DeleteDialogListener) activity;
        } catch (ClassCastException e) {
            // The activity doesn't implement the interface, throw exception
            throw new ClassCastException(activity.toString()
                    + " must implement NoticeDialogListener");
        }
    }
	
	
	@Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the Builder class for convenient dialog construction
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        if(callingActivity.equals("Medications"))
        	builder.setMessage("Delete Medication?");
        else if(callingActivity.equals("MedicationInfo"))
        	builder.setMessage("Delete Dose?");
        else if(callingActivity.equals("DoctorInfo"))
        	builder.setMessage("Delete Doctor?");
        else if(callingActivity.equals("ContactInfo"))
        	builder.setMessage("Delete Contact?");
        else if(callingActivity.equals("Notes"))
        	builder.setMessage("Delete Note?");
        else
        	builder.setMessage("Delete?");
        
            builder.setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                	   mListener.onPositiveClick();
                   }
               })
               .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                	   DeleteDialogFragment.this.getDialog().cancel();
                   }
               });
        // Create the AlertDialog object and return it
        return builder.create();
    }
}
